#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

#define NUM 128
#define CMD_NUM 64

int main()
{
    char command[NUM];
    for(; ;){
        char *argv[CMD_NUM] = {NULL};
        //1.打印提示符
        command[0] = 0;
        printf("[mlg@myhostname myshell]# ");
        //2.获命令字符串
        fgets(command, NUM, stdin);
        command[strlen(command) - 1] = '\0';
        //printf("echo：%s\n",command);
        
        //"ls -a -l -b -c\0"
        //3.解析命令字符串
        const char* sep = " ";
        argv[0] = strtok(command, sep);
        int i = 1;
        while(argv[i] = strtok(NULL, sep)){
          i++;
        }

        //4.检测命令是否需要shell本身执行，内建命令
        if(strcmp(argv[0], "cd") == 0){
            if(argv[1] != NULL){
                chdir(argv[1]);
            }
            continue;
        }
        
        //5.执行第三方命令
        if(fork() == 0){
            execvp(argv[0], argv);
            exit(1);
        }

        int status = 0;
        waitpid(-1, &status, 0);
        printf("exit code：%d\n",(status >> 8) & 0xFF);
    }
}
